package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Playlist;
import model.Song;

public final class PlaylistEditUI extends BaseJFrame {

    //private fields
    private final EntityManager entityManager;
    private final Playlist selectedPlaylist;
    private Song selectedSong;

    public PlaylistEditUI(Playlist selectedPlaylist, EntityManager entityManager) {
        this.entityManager = entityManager;

        this.selectedPlaylist = selectedPlaylist;

        initComponents();

        if (selectedPlaylist != null) {
            createdDateDC.setDate(selectedPlaylist.getCreationDate());
        }

        // display in the center of the window
        setLocationRelativeTo(null);

        bindSongTable();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        playlist1 = selectedPlaylist;
        songList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(playlist1.getSongList());
        jLabel2 = new javax.swing.JLabel();
        createdDateDC = new com.toedter.calendar.JDateChooser();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        songTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        descriptionTa = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        nameTF = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jLabel2.setText("Διαχείριση Λίστας");

        jButton3.setText("Αποθήκευση");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveMusicGroup(evt);
            }
        });

        jButton4.setText("Ακύρωση");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelForm(evt);
            }
        });

        jLabel7.setText("Ημερομηνία δημιουργίας");

        songTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Τίτλος", "Καλλιτέχνης", "Διάρκεια"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(songTable);

        jButton1.setText("Εισαγωγή");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertSong(evt);
            }
        });

        jButton2.setText("Διαγραφή");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteSong(evt);
            }
        });

        jLabel8.setText("Περιγραφή");

        descriptionTa.setColumns(20);
        descriptionTa.setRows(5);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playlist1, org.jdesktop.beansbinding.ELProperty.create("${description}"), descriptionTa, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jScrollPane2.setViewportView(descriptionTa);

        jLabel1.setText("Όνομα");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playlist1, org.jdesktop.beansbinding.ELProperty.create("${name}"), nameTF, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(227, 227, 227)
                                .addComponent(jButton3)
                                .addGap(18, 18, 18)
                                .addComponent(jButton4))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(139, 139, 139)
                                .addComponent(jLabel2))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel8)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                                    .addComponent(nameTF))))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addGap(18, 18, 18)
                                .addComponent(createdDateDC, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 414, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButton1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButton2))))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel2)
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(nameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(createdDateDC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private boolean containsDoubleTitles() {

        boolean duplicateTitleExists = songList.stream()
                .anyMatch(c -> songList.stream()
                        .anyMatch(d -> c.getTitle().equals(d.getTitle())
                                && c.getSongId() != null && d.getSongId() != null
                                && !c.getSongId().equals(d.getSongId())));

        return duplicateTitleExists;
    }

    private void saveMusicGroup(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMusicGroup

        // at least one song per album
        if (songList.isEmpty()) {
            showWarningMessage("Η λίστα δεν περιέχει τραγούδια");
            return;
        }
        // no duplicate ttles allowed
        if (containsDoubleTitles()) {
            showWarningMessage("Υπάρχουν τραγούδια με το ίδιο όνομα");
            return;
        }

        if (playlist1.getName().equals("")) {
            showWarningMessage("Το όνομα της λίστας πρέπει να έχει όνομα");
            return;
        }

        if (playlist1.getDescription().equals("")) {
            showWarningMessage("Πρέπει να εισάγεις περγραφή");
            return;
        }
         
        int duration=0;
        duration = playlist1.getSongList().stream().map((song) -> song.getDuration()).reduce(duration, Integer::sum);

        if (duration < 1800) {
            showWarningMessage("Η λίστα πρέπει να έχει συνολική διάρκεια τουλάχιστον μισή ώρα");
            return;
        }

        selectedPlaylist.setCreationDate(createdDateDC.getDate());
        closeFrame(true);
    }//GEN-LAST:event_saveMusicGroup

    private void cancelForm(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelForm
        closeFrame(false);
    }//GEN-LAST:event_cancelForm

    public void setSelectedSong(Song selectedSong) {
        this.selectedSong = selectedSong;
    }

    public void bindSongTable() {

        DefaultTableModel defaultTableModel = (DefaultTableModel) songTable.getModel();
        defaultTableModel.setRowCount(playlist1.getSongList().size());

        // for each song
        for (int i = 0; i < playlist1.getSongList().size(); i++) {
            // Πάρε τις πληροφορίες του
            String title = playlist1.getSongList().get(i).getTitle();
            String singers = "";
            if (playlist1.getSongList().get(i).getAlbum() != null) {
                if (playlist1.getSongList().get(i).getAlbum().getArtist() != null) {
                    singers += playlist1.getSongList().get(i).getAlbum().getArtist().getArtisticName();
                }

                if (singers.length() > 0) {
                    singers += ", ";
                }

                if (playlist1.getSongList().get(i).getAlbum().getMusicGroup() != null) {
                    singers += playlist1.getSongList().get(i).getAlbum().getMusicGroup().getName();
                }
            }
            int duration = playlist1.getSongList().get(i).getDuration();

            // display info in table
            defaultTableModel.setValueAt(title, i, 0);
            defaultTableModel.setValueAt(singers, i, 1);
            defaultTableModel.setValueAt(duration, i, 2);
        }
    }

    private void insertSong(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertSong
        SelectSongForm selectSongForm = new SelectSongForm(entityManager, playlist1.getSongList(), this);
        selectSongForm.setVisible(true);
        setEnabled(false);

        selectSongForm.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                if (((MyWindowEvent) arg0).exitAndSave) {

                    // check if song already exists in list
                    if (playlist1.getSongList().contains(selectedSong)) {
                        showWarningMessage("Το τραγούδι υπάρχει ήδη στην λίστα");
                    } else {
                        // insert song in list
                        playlist1.getSongList().add(selectedSong);
                        selectedSong.getPlaylistList().add(playlist1);

                        bindSongTable();

                        // select song in list
                        int row = playlist1.getSongList().size() - 1;
                        songTable.setRowSelectionInterval(row, row);
                        songTable.scrollRectToVisible(songTable.getCellRect(row, 0, true));
                    }
                }
                setEnabled(true);
            }

            public void windowActivated(WindowEvent arg0) {
            }

            public void windowClosing(WindowEvent arg0) {
            }

            public void windowDeactivated(WindowEvent arg0) {
            }

            public void windowDeiconified(WindowEvent arg0) {
            }

            public void windowIconified(WindowEvent arg0) {
            }

            public void windowOpened(WindowEvent arg0) {
            }
        });

    }//GEN-LAST:event_insertSong

    private void deleteSong(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSong
        // get selected song
        int selectedRow = songTable.getSelectedRow();

        // in case not selected song
        if (selectedRow == -1) {
            showWarningMessage("Δεν έχει επιλεχθεί τραγούδι");
            return;
        }
        int choice = showPrompt("Επιβεβαίωση διαγραφής τραγουδιού", "Διαγραφή του τραγουδιού;");
        if (choice != 0) {
            return;
        }

        // get selected song
        Song selectedSong = playlist1.getSongList().get(selectedRow);

        // remove from list
        playlist1.getSongList().remove(selectedSong);
        selectedSong.getPlaylistList().remove(playlist1);

        bindSongTable();
    }//GEN-LAST:event_deleteSong


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.JDateChooser createdDateDC;
    private javax.swing.JTextArea descriptionTa;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField nameTF;
    private model.Playlist playlist1;
    private java.util.List<model.Song> songList;
    private javax.swing.JTable songTable;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
